//
//  dynamicsVC.m
//  DingDing
//
//  Created by LHL on 14/12/2.
//  Copyright (c) 2014年 com.gordon. All rights reserved.
//

#import "dynamicsVC.h"
#import "AreaCell.h"
#import "AddImageCell.h"
#import "dynamicsVC.h"
#import "PhotoTableViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AppBoard_iPhone.h"
#define SP_SCREEN_SCALE() ([UIScreen mainScreen].scale)
@interface dynamicsVC ()

@end

@implementation dynamicsVC{
    
    __weak IBOutlet UITableView *_tableview;
    AreaCell *are;
    __weak IBOutlet UIButton *weibo;
    NSMutableArray *photoArray;
//    NSMutableArray *photoIndex;
    UIButton *rightbutton;
    NSMutableArray *_group;
}
DEF_MODEL(postdynamics, ipostdynamics)

-(void)load{
    
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    _group = [[NSMutableArray alloc]init];
    self.ipostdynamics = [postdynamics modelWithObserver:self];
    self.navigationBarShown = YES;
    rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbutton.frame = CGRectMake(0, 0, 40, 40);
    [rightbutton addTarget:self action:@selector(publishDynm) forControlEvents:UIControlEventTouchUpInside];
    [rightbutton setTitle:@"发布" forState:0];
    [rightbutton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [rightbutton setTitleColor:[UIColor whiteColor] forState:0];
    [rightbutton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightbutton];
    self.title = @"发布动态";
    rightbutton.enabled = NO;
    self.navigationBarLeft = [UIImage imageNamed:@"back.png"];
    self.navigationItem.hidesBackButton = YES;
    photoArray = [[NSMutableArray alloc]init];
//    photoIndex = [[NSMutableArray alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addPhotoFunc:) name:@"photo" object:nil];
    [_tableview registerClass:[AddImageCell class] forCellReuseIdentifier:@"addimage"];
    
}

-(void)dealloc{
    [super dealloc];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

ON_WILL_APPEAR(SIGNAL){
    self.navigationItem.hidesBackButton = YES;
    [[AppBoard_iPhone sharedInstance] dismissTips];
}

-(void)checkparm{
    AreaCell *areacell = (AreaCell *)[_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (areacell.areView.text.length == 0 && photoArray.count == 0) {
        rightbutton.enabled = NO;
    }else{
        rightbutton.enabled = YES;
    }
}

-(void)publishDynm{
    AreaCell *areacell = (AreaCell *)[_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    self.ipostdynamics.text = areacell.areView.text;
    NSMutableArray *temp = [[NSMutableArray alloc]init];
    for (int i = 0; i < photoArray.count; i++) {
        UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfFile:photoArray[i]]];
//        UIImage *final = [Common imageWithImageSimple:img scaledToSize:CGSizeMake(960, (960/img.size.width)*img.size.height)];
        UIImage *final = [self imageCompressForSize:img targetSize:CGSizeMake(960, (960/img.size.width)*img.size.height)];
        NSInteger imglength = [UIImageJPEGRepresentation(final, 1.0) length];
        NSData *small = UIImageJPEGRepresentation(final, (imglength %110)/imglength);
        NSLog(@"%d",small.length);
        [temp addObject:[UIImage imageWithData:small]];
    }
    self.ipostdynamics.imgData = temp;
    [self.ipostdynamics firstPage];

}

-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


ON_SIGNAL3(postdynamics, RELOADING, SIGNAL){
    [self presentLoadingTips:@"发布中"];
}

ON_SIGNAL3(postdynamics, RELOADED, SIGNAL){
    [self dismissTips];
    [self presentMessageTips:@"发布成功"];
    [self performSelector:@selector(popFunc) withObject:nil afterDelay:1.0];
}
-(void)popFunc{
    [self.navigationController popViewControllerAnimated:YES];
}

ON_SIGNAL3(postdynamics, FAILED, SIGNAL){
    [self dismissTips];
    [self presentMessageTips:@"发布失败"];
}

-(void)addPhotoFunc:(NSNotification *)sender{
    AddImageCell *cell = (AddImageCell *)[_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSArray *photo = sender.object;
    [photoArray removeAllObjects];
    [photoArray addObjectsFromArray:[NSArray arrayWithArray:photo]];
    [_tableview beginUpdates];
    for (int i = 0; i < 9; i++) {
         UIImageView *v = (UIImageView *)[cell.contentView viewWithTag:11000+i];
        UIButton *deletebutton = (UIButton *)[cell.contentView viewWithTag:11120+i];
        if (i < photoArray.count) {
            v.frame = CGRectMake(10+76*(i%4), 10+76*(i/4), 70, 70);
            v.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:photoArray[i]]];
            deletebutton.frame = CGRectMake(v.frame.size.width-10+v.frame.origin.x,v.frame.origin.y-5, 15, 15);
            
        }else{
            v.image = nil;
            v.frame = CGRectZero;
            deletebutton.frame = CGRectZero;
        }
    }
    if (photoArray.count !=0) {
        if (photoArray.count == 9) {
            cell.addImage.hidden = YES;
        }else{
            cell.addImage.frame = CGRectMake(10+76*(photoArray.count%4), 10+76*(photoArray.count/4), 70, 70);
        }
    }else{
        cell.addImage.frame = CGRectMake(10, 10, 70, 70);
    }
    [_tableview endUpdates];
    [self checkparm];
}

-(void)viewWillAppear:(BOOL)animated{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)weibotouchDown:(UIButton *)sender {
    sender.selected = !sender.selected;
    
}

//添加图片
-(void)addImageFunc{
    UIStoryboard *st = [UIStoryboard storyboardWithName:@"PersonalHome" bundle:nil];
    PhotoTableViewController *vc = [st instantiateViewControllerWithIdentifier:@"photoVC"];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:vc];
    [self.navigationController presentViewController:navigationController animated:YES completion:nil];
    
}

#pragma mark - TableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 120;
    }
    if (photoArray.count == 0) {
        return 90;
    }else{
        if (photoArray.count >4) {
            if (photoArray.count %4 >0) {
                return ((photoArray.count/4)+1) * 90;
            }else{
                return (photoArray.count/4) * 90;
            }
        }else{
            return 90;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        are = [tableView dequeueReusableCellWithIdentifier:@"area"];
        return are;
    }
    AddImageCell *addimg = [tableView dequeueReusableCellWithIdentifier:@"addimage"];
    addimg.selectionStyle = UITableViewCellSelectionStyleNone;
    [addimg.addImage addTarget:self action:@selector(addImageFunc) forControlEvents:UIControlEventTouchUpInside];
    [addimg getDeleteInteger:^(NSInteger tag){
        if ([[NSFileManager defaultManager] removeItemAtPath:photoArray[tag] error:nil]) {
            NSLog(@"删除成功");
        }else{
            NSLog(@"删除失败");
        }
        [photoArray removeObjectAtIndex:tag];
        for (int i = 0; i < 9; i++) {
            UIImageView *v = (UIImageView *)[addimg.contentView viewWithTag:11000+i];
            UIButton *deletebutton = (UIButton *)[addimg.contentView viewWithTag:11120+i];
            if (i < photoArray.count) {
                v.frame = CGRectMake(10+76*(i%4), 10+76*(i/4), 70, 70);
                v.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:photoArray[i]]];
                deletebutton.frame = CGRectMake(v.frame.size.width-10+v.frame.origin.x,v.frame.origin.y-5, 15, 15);
            }else{

                v.image = nil;
                v.frame = CGRectZero;
                deletebutton.frame = CGRectZero;
//                deletebutton.hidden = YES;
            }
        }
        if (photoArray.count !=0) {
            addimg.addImage.hidden = NO;
            if (photoArray.count == 9) {
                addimg.addImage.hidden = YES;
            }else{
                addimg.addImage.frame = CGRectMake(10+76*(photoArray.count%4), 10+76*(photoArray.count/4), 70, 70);
            }
        }else{
            addimg.addImage.frame = CGRectMake(10, 10, 70, 70);
        }
        [_tableview endUpdates];
        [self checkparm];
    }];
    return addimg;
}

#pragma mark - TextView

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [are.areView resignFirstResponder];
        return NO;
    }
    if (text.length + textView.text.length >=140) {
        return NO;
    }
    if (textView.text.length >0) {
        are.placehoderLabel.hidden = YES;
    }
    if (textView.text.length == 1) {
        if ([text isEqualToString:@""]) {
            if (photoArray.count == 0) {
                rightbutton.enabled = NO;
            }else{
                rightbutton.enabled = YES;
            }
            are.placehoderLabel.hidden = NO;
        }else{
            are.placehoderLabel.hidden = YES;
        }
    }

    if (textView.text.length == 0) {
        if (text.length >0) {
            rightbutton.enabled = YES;
            are.placehoderLabel.hidden = YES;
        }else{
            if (photoArray.count == 0) {
                rightbutton.enabled = NO;
            }else{
                rightbutton.enabled = YES;
            }
            are.placehoderLabel.hidden = NO;
        }
    }
    
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self checkparm];
    [are.areView resignFirstResponder];
}



@end
